import React, { useState } from 'react';
import { Button, Modal, Form, Input, message } from 'antd';
import localForage from 'localforage';
import { RuleObject } from 'antd/es/form';

interface CardConfig {
    title: string;
    gridItems: { text: string; link: string }[];
}

interface AddCardButtonProps {
    onAdd: (newCard: CardConfig) => Promise<void>;
}

const AddCardButton: React.FC<AddCardButtonProps> = ({ onAdd }) => {
    const [visible, setVisible] = useState(false);
    const [form] = Form.useForm();

    const handleSubmit = async (values: {
        title: string;
        items: string;
    }) => {
        try {
            const gridItems = values.items.split('\n')
                .filter(text => text.trim())
                .map(text => ({
                    text: text.trim(),
                    link: `/${text.toLowerCase().replace(/\s+/g, '-')}`
                }));

            await onAdd({
                title: values.title,
                gridItems
            });

            message.success('卡片添加成功');
            setVisible(false);
            form.resetFields();
        } catch (err) {
            message.error('添加失败，请重试');
        }
    };

    return (
        <>
            <Button
                type="primary"
                onClick={() => setVisible(true)}
                style={{ marginBottom: 16 }}
            >
                新增卡片
            </Button>

            <Modal
                title="新建卡片"
                open={visible}
                onCancel={() => setVisible(false)}
                onOk={() => form.submit()}
            >
                <Form form={form} onFinish={handleSubmit}>
                    <Form.Item
                        label="卡片标题"
                        name="title"
                        rules={[{ required: true, message: '请输入标题' }]}
                    >
                        <Input placeholder="例如：数据管理" />
                    </Form.Item>

                    <Form.Item
                        label="卡片项（每行一个）"
                        name="items"
                        rules={[
                            {
                                required: true,
                                message: '请输入至少一个卡片项',
                                validator: (rule: RuleObject, value: string) => {
                                    const items = value?.split('\n').filter(t => t.trim());
                                    return items?.length > 0
                                        ? Promise.resolve()
                                        : Promise.reject(new Error('至少需要输入一个有效卡片项'));
                                }
                            }
                        ]}
                    >
                        <Input.TextArea
                            rows={4}
                            placeholder={`例如：数据上传\n数据管理\n数据导出`}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default AddCardButton;
